<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="租户名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入租户名" />
      </el-form-item>
      <el-form-item label="租户套餐" prop="packageId">
        <el-select
          v-model="formData.packageId"
          :empty-values="['', null, undefined]"
          clearable
          placeholder="请选择租户套餐">
          <el-option
            v-for="_package in packageList"
            :key="_package.id"
            :value="_package.id"
            :label="_package.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系人" prop="contactName">
        <el-input v-model="formData.contactName" placeholder="请输入联系人" />
      </el-form-item>
      <el-form-item label="联系手机" prop="contactMobile">
        <el-input v-model="formData.contactMobile" placeholder="请输入联系手机" />
      </el-form-item>
      <el-form-item v-if="formType === 'create'" label="用户账号" prop="loginName">
        <el-input v-model="formData.loginName" placeholder="请输入用户账号" autocomplete="off" />
      </el-form-item>
      <el-form-item v-if="formType === 'create'" label="用户密码" prop="password">
        <el-input v-model="formData.password" type="password" placeholder="请输入用户密码" autocomplete="off" />
      </el-form-item>
      <el-form-item label="绑定域名" prop="website">
        <el-input v-model="formData.website" placeholder="请输入绑定域名" />
      </el-form-item>
      <el-form-item label="账号额度" prop="accountCount">
        <el-input-number v-model="formData.accountCount" :min="1" controls-position="right" placeholder="请输入账号额度" />
      </el-form-item>
      <el-form-item label="过期时间" prop="expireTime">
        <el-date-picker
          v-model="formData.expireTime"
          type="date"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择过期时间"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in common_enable_status"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
      <template #footer>
          <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
      </template>
  </Dialog>
</template>

<script setup lang="ts">
import { TenantApi, TenantVO } from '@/api/system/tenant/tenant'
import { TenantPackageApi, TenantPackageVO } from '@/api/system/tenant/tenant_package'
import { FormRules } from 'element-plus'
import {EnableStatusEnum} from "@/utils/constants";

defineOptions({ name: 'SystemTenantForm' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const { common_enable_status } = useIntDict( DICT_TYPE.common_enable_status )

const dialogVisible = ref(false) // dialog是否展示
const dialogTitle = ref('') // dialog标题
const formLoading = ref(false) // 表单加载中标记，1. 修改时的数据加载，2. 提交的按钮禁用
const formType = ref('') // 表单类型，新增：create，修改：update
const formDataObj = {
  id: undefined,
  name: undefined,
  contactName: undefined,
  contactMobile: undefined,
  loginName: undefined,
  password: undefined,
  website: undefined,
  packageId: undefined,
  accountCount: undefined,
  expireTime: undefined,
  status: EnableStatusEnum.Enabled
}
const formData = ref({ ...formDataObj })
const formRules = reactive<FormRules>({
  name: [{ required: true, message: '租户名不能为空', trigger: 'blur' }],
  contactName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  contactMobile: [
    {
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  loginName: [{ required: true, message: '用户账号不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }],
  website: [{ required: true, message: '绑定域名不能为空', trigger: 'blur' }],
  packageId: [{ required: true, message: '租户套餐不能为空', trigger: 'change' }],
  accountCount: [{ required: true, message: '账号数量不能为空', trigger: 'blur' }],
  expireTime: [{ required: true, message: '过期时间不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const packageList = ref([] as TenantPackageVO[])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id != undefined) {
    formLoading.value = true
    try {
      formData.value = await TenantApi.getTenant(id)
    } finally {
      formLoading.value = false
    }
  }
  packageList.value = await TenantPackageApi.getTenantPackageSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success']) // 定义success事件，用于操作成功后的回调
const submitForm = async () => {
  if (await formValidate(formRef)) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TenantVO
    if (formType.value === 'create') {
      await TenantApi.createTenant(data)
      message.success(t('common.createSuccess'))
    } else {
      await TenantApi.updateTenant(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = { ...formDataObj }
  formRef.value?.resetFields()
}
</script>

<style scoped lang="scss"></style>
